package com.jf.design.strategy;

import com.jf.design.strategy.bean.BaseParams;
import com.jf.design.strategy.bean.ResultSet;
import com.jf.design.strategy.bean.StrategyNameEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略执行入口
 *
 * @author Yunfeng
 */
@Slf4j
@Service
public class StrategyExexutor implements ApplicationContextAware {

    /**
     * 策略实例存储
     */
    public Map<StrategyNameEnum, StrategyPattern<BaseParams, ResultSet>> map = new HashMap<>();

    /**
     * 提供给外部 执行策略的 入口方法
     *
     * @param nameEnum 策略名
     * @param t        参数
     * @return R 结果
     */
    public ResultSet doStrategy(StrategyNameEnum nameEnum, BaseParams t) {
        return map.get(nameEnum).execute(t);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // ？？？ 没有泛型 不确定是否没问题
        Map<String, StrategyPattern> beansOfType = applicationContext.getBeansOfType(StrategyPattern.class);
        for (StrategyPattern value : beansOfType.values()) {
            map.put(value.getStrategyName(), value);
        }
    }
}
